﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using WillCallLib;
using WillCallWeb;
using WillCallWeb.BaseClasses;



public partial class HostsControl : BaseUserControl
    {
        public override object Item
        {
            get
            {
                return new Host()
                {
                    Name = txtName.Text,
                    Phone = txtPhone.Text,
                    Email = txtEmail.Text,
                    Id = Key
                };
            }
            set
            {
                var host = value as Host;
                txtName.Text = host.Name;
                txtPhone.Text = host.Phone;
                txtEmail.Text = host.Email;
            }
        }
        public override int Key
        {
            get
            {
                return lstHosts.SelectedIndex == -1 ? default(int) : int.Parse(lstHosts.SelectedValue);
            }
            set
            {
                lstHosts.SelectedValue = value.ToString();
            }
        }

        public override void ChangeMode()
        {
            pnlHostsEdit.Visible = Mode == Modes.Edit;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack) FillList();
        }

        protected void lstHosts_SelectedIndexChanged(object sender, EventArgs e)
        {
            Item = ctx.Hosts.Find(Key);
            OnItemSelected(Key);
        }

        protected void cmdAdd_Click(object sender, EventArgs e)
        {
            Host h = Item as Host;
            ctx.Hosts.Add(h);
            ctx.SaveChanges();
            FillList();
        }
        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            if (lstHosts.SelectedIndex == -1) return;
            ctx.Hosts.Remove(ctx.Hosts.Find(Key));
            ctx.SaveChanges();
            FillList();
        }

        protected void cmdUpdate_Click(object sender, EventArgs e)
        {
            if (lstHosts.SelectedIndex == -1) return;
            Host h = Item as Host;
            h.Id = int.Parse(lstHosts.SelectedValue);
            ctx.Hosts.Attach(h);
            ctx.Entry(h).State = EntityState.Modified;
            ctx.SaveChanges();
            FillList();
        }

        private void FillList()
        {
            lstHosts.DataSource = ctx.Hosts.ToList();
            lstHosts.DataBind();
            ClearForm();
        }

        private void ClearForm()
        {
            txtName.Text = "";
            txtPhone.Text = "";
            txtEmail.Text = "";
        }


        protected void cbMode_CheckedChanged(object sender, EventArgs e)
        {
            Mode = cbMode.Checked == true ? Modes.Edit : Modes.List;
        }
    }
